package com.example.demo.config;

import java.lang.reflect.Method;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;


@Configuration //通过注解@Configuration来表明该类是一个Spring的配置，相当于一个xml文件
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
	
	@Bean
	public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
	
//	@Bean
//	public RedisCacheConfiguration redisCacheConfiguration() {
//	    return RedisCacheConfiguration
//	            .defaultCacheConfig()
//	            .serializeKeysWith(
//	                    RedisSerializationContext
//	                            .SerializationPair
//	                            .fromSerializer(new StringRedisSerializer()))
//	            .serializeValuesWith(
//	                    RedisSerializationContext
//	                            .SerializationPair
//	                            .fromSerializer(new Jackson2JsonRedisSerializer<>(Object.class)));
//	}
	
	@Bean 
	@ConditionalOnMissingBean(StringRedisTemplate.class)
		public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) { 
		StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(); 
		stringRedisTemplate.setConnectionFactory(factory); 
		return stringRedisTemplate; 
	} 
	  
	@Bean 
	@ConditionalOnMissingBean(name = "redisTemplate")
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { 
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); 
		redisTemplate.setConnectionFactory(factory); 
		return redisTemplate; 
	} 

		
//		@Bean
//		public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
//		    RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory).build();
//		    return redisCacheManager;
//		}
}